#!/usr/bin/env bash

cat > /root/.my.cnf << EOF
[client]
user = homestead
password = secret
host = localhost
EOF

cp /root/.my.cnf /home/vagrant/.my.cnf

# MySQL 配置文件路径（根据实际安装情况修改路径）
MY_CNF_PATH="/etc/mysql/my.cnf"

# 检查并修改 my.cnf 文件
if [ -f "$MY_CNF_PATH" ]; then
    echo "Found $MY_CNF_PATH, proceeding with modification..."

    # 检查 sql_mode 配置是否已存在，如果不存在则添加
    if ! grep -q "sql_mode" "$MY_CNF_PATH"; then
        echo "sql_mode not found, adding it to my.cnf..."
        # 在 [mysqld] 配置块中添加 sql_mode 设置
        echo -e "\n[mysqld]\nsql_mode=STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION" | sudo tee -a "$MY_CNF_PATH" > /dev/null
    else
        # 如果已存在 sql_mode，直接修改其值
        echo "sql_mode found, updating its value..."
        sudo sed -i 's/^sql_mode.*/sql_mode=STRICT_TRANS_TABLES,NO_ENGINE_SUBSTITUTION/' "$MY_CNF_PATH"
    fi

    # 重启 MySQL 服务使配置生效
    sudo systemctl restart mysql
    echo "MySQL service restarted. sql_mode has been updated."
else
    echo "$MY_CNF_PATH not found. Please verify your MySQL configuration file path."
    exit 1
fi

DB=$1;

mysql=$(pidof mysqld)
mariadb=$(pidof mariadbd)

if [ -z "$mysql" ]
then
      # Skip Creating MySQL database
      echo "We didn't find a PID for mysqld, skipping \$DB creation"
else
      mysql -e "CREATE DATABASE IF NOT EXISTS \`$DB\` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci";
fi

if [ -z "$mariadb" ]
then
      # Skip Creating MariaDB database
      echo "We didn't find a PID for mariadb, skipping \$DB creation"
else
      mysql -e "CREATE DATABASE IF NOT EXISTS \`$DB\` DEFAULT CHARACTER SET utf8mb4 DEFAULT COLLATE utf8mb4_unicode_ci";
fi
